package com.wanmait.computershop.dao;

import com.wanmait.computershop.util.DBhelper;
import com.wanmait.computershop.vo.CateGory;
import com.wanmait.computershop.vo.Product;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class WebShowProductDao {
    //查询所有商品信息
    public List<Product> findProducts(){
        QueryRunner queryRunner = new QueryRunner(DBhelper.getDruidDataSource());
        String sql = "SELECT *,category_id AS categoryId,item_type AS itemType,sell_point AS sellPoint from product";

        try {
//            List<Product> productList  = queryRunner.query(sql,new BeanListHandler<>(Product.class),categoryId);
            List<Product> productList  = queryRunner.query(sql,new BeanListHandler<>(Product.class));
            return productList;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } 
        return null;
    }
    //根据商品分类查询商品
    public List<Product> findProductsByCategory(Integer categoryId){
        QueryRunner queryRunner = new QueryRunner(DBHelper.getDruidDataSource());
        String sql = "SELECT a.*,a.category_id AS categoryId,a.item_type AS itemType,a.sell_point AS sellPoint  \n" +
                "from product a,category b\n" +
                "WHERE a.category_id = b.id and\n" +
                "b.parent_id=?";
        try {
            List<Map<String,Object>> mapproductList = queryRunner.query(sql,new MapListHandler(),categoryId);
            
            List<Product> productList = new ArrayList<>();
            //mapList-->map-->product-->productList
            for (Map<String,Object> map:mapproductList)
            {
                Product product = new Product();
                productList.add(product);
                
                product.setId((Integer)map.get("id"));
                product.setCategoryId((Integer)map.get("categoryId"));
                product.setItemType((String)map.get("item_type"));
                product.setTitle((String)map.get("title"));
                product.setSellPoint((String)map.get("sellPoint"));
                product.setPrice((Integer)map.get("price"));
                product.setStocknum((Integer)map.get("num"));
                product.setImage((String)map.get("image"));
                product.setEnable((Integer)map.get("enable"));
                product.setPriority((Integer)map.get("priority"));

                CateGory cateGory = new CateGory();
                
                product.setCateGory(cateGory);
            }
            
            return productList;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}
